using System;

namespace Mysoft.Dbf.Writers
{
    public class NumericFieldWriter : FieldWriterBase
    {

        public NumericFieldWriter(string columnName, byte totalLength, byte decimalPlaces)
            :
            base(columnName, 'N', totalLength, decimalPlaces)
        {
        }

        protected override string FormatValueAsString(object value)
        {
            decimal decimalValue = Decimal.Parse(value.ToString());
            string stringToWrite = Decimal.Truncate(decimalValue).ToString().Trim();
            if (this.DecimalPlaces > 0)
                stringToWrite = stringToWrite + "." + GetDecimalsString(decimalValue);
            if (stringToWrite.Length > this.TotalSize)
                throw new ApplicationException("Value " + stringToWrite + " requires a " + stringToWrite.Length + " length column and could not be written in the " + this.ColumnName + " column that has only " + this.TotalSize.ToString() + " characters total capacity");
            stringToWrite = stringToWrite.PadLeft(this.TotalSize, ' ');

            return stringToWrite;
        }

        private string GetDecimalsString(decimal value)
        {
            string format = ".".PadRight(1 + this.DecimalPlaces, '0');
            if (value < 0)
                value = value * -1;
            string rez = (value - Decimal.Truncate(value)).ToString(format);
            rez = rez.Replace(".", "");
            if (rez.Length > this.DecimalPlaces)
                rez = rez.Substring(0, this.DecimalPlaces);
            rez = rez.PadRight(this.DecimalPlaces, '0');
            return rez;
        }
    }
}
